

import React, { useState, useCallback } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList, Modal, RefreshControl, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome5, FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';

interface ApprovalItem {
  id: string;
  title: string;
  createTime: string;
  status: 'pending' | 'processing' | 'approved' | 'rejected';
  currentStep?: string;
  reason?: string;
}

type FilterStatus = 'all' | 'pending' | 'processing' | 'approved' | 'rejected';
type SortType = 'time-desc' | 'time-asc' | 'status';

const MyInitiatedScreen = () => {
  const router = useRouter();
  
  // 搜索相关状态
  const [isSearchVisible, setIsSearchVisible] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  
  // 筛选相关状态
  const [isFilterModalVisible, setIsFilterModalVisible] = useState(false);
  const [selectedFilterStatus, setSelectedFilterStatus] = useState<FilterStatus>('all');
  const [selectedSortType, setSelectedSortType] = useState<SortType>('time-desc');
  
  // 列表相关状态
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  
  // 模拟数据
  const [approvalList, setApprovalList] = useState<ApprovalItem[]>([
    {
      id: 'PI001',
      title: '员工培训申请',
      createTime: '2024-01-15 14:30',
      status: 'processing',
      currentStep: '部门经理审批',
    },
    {
      id: 'PI002',
      title: '办公设备采购',
      createTime: '2024-01-14 10:15',
      status: 'approved',
    },
    {
      id: 'PI003',
      title: '差旅费用报销',
      createTime: '2024-01-13 16:45',
      status: 'pending',
    },
    {
      id: 'PI004',
      title: '项目预算申请',
      createTime: '2024-01-12 09:20',
      status: 'processing',
      currentStep: '财务总监审批',
    },
    {
      id: 'PI005',
      title: '会议室预订',
      createTime: '2024-01-11 11:30',
      status: 'rejected',
      reason: '时间冲突',
    },
    {
      id: 'PI006',
      title: '加班申请',
      createTime: '2024-01-10 18:20',
      status: 'approved',
    },
  ]);

  // 搜索功能
  const handleSearchPress = useCallback(() => {
    setIsSearchVisible(true);
  }, []);

  const handleSearchClose = useCallback(() => {
    setIsSearchVisible(false);
    setSearchKeyword('');
  }, []);

  const handleSearchChange = useCallback((text: string) => {
    setSearchKeyword(text);
  }, []);

  // 筛选功能
  const handleFilterPress = useCallback(() => {
    setIsFilterModalVisible(true);
  }, []);

  const handleFilterClose = useCallback(() => {
    setIsFilterModalVisible(false);
  }, []);

  const handleFilterStatusSelect = useCallback((status: FilterStatus) => {
    setSelectedFilterStatus(status);
  }, []);

  const handleSortTypeSelect = useCallback((sortType: SortType) => {
    setSelectedSortType(sortType);
  }, []);

  const handleFilterApply = useCallback(() => {
    // 这里可以添加应用筛选的逻辑
    console.log('应用筛选:', { 
      status: selectedFilterStatus, 
      sort: selectedSortType 
    });
    setIsFilterModalVisible(false);
  }, [selectedFilterStatus, selectedSortType]);

  // 列表项点击
  const handleApprovalItemPress = useCallback((item: ApprovalItem) => {
    router.push(`/p-approval_detail?processInstanceId=${item.id}`);
  }, [router]);

  // 下拉刷新
  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    try {
      // 模拟刷新数据
      await new Promise(resolve => setTimeout(resolve, 1000));
      console.log('执行下拉刷新');
    } catch (error) {
      Alert.alert('错误', '刷新失败，请重试');
    } finally {
      setIsRefreshing(false);
    }
  }, []);

  // 加载更多
  const handleLoadMore = useCallback(async () => {
    if (isLoadingMore) return;
    
    setIsLoadingMore(true);
    try {
      // 模拟加载更多数据
      await new Promise(resolve => setTimeout(resolve, 1000));
      console.log('加载更多数据');
    } catch (error) {
      Alert.alert('错误', '加载失败，请重试');
    } finally {
      setIsLoadingMore(false);
    }
  }, [isLoadingMore]);

  // 获取状态文本和样式
  const getStatusInfo = (status: ApprovalItem['status']) => {
    switch (status) {
      case 'pending':
        return { text: '待审批', style: styles.statusPending };
      case 'processing':
        return { text: '审批中', style: styles.statusProcessing };
      case 'approved':
        return { text: '已通过', style: styles.statusApproved };
      case 'rejected':
        return { text: '已驳回', style: styles.statusRejected };
      default:
        return { text: '未知', style: styles.statusPending };
    }
  };

  // 获取状态图标
  const getStatusIcon = (item: ApprovalItem) => {
    switch (item.status) {
      case 'approved':
        return <FontAwesome5 name="check-circle" size={12} color="#10B981" />;
      case 'rejected':
        return <FontAwesome5 name="times-circle" size={12} color="#EF4444" />;
      case 'pending':
        return <FontAwesome6 name="clock" size={12} color="#F59E0B" />;
      case 'processing':
        return <FontAwesome5 name="map-marker-alt" size={12} color="#6B7280" />;
      default:
        return null;
    }
  };

  // 获取状态描述
  const getStatusDescription = (item: ApprovalItem) => {
    switch (item.status) {
      case 'approved':
        return '流程已完成';
      case 'rejected':
        return item.reason || '已驳回';
      case 'pending':
        return '等待处理';
      case 'processing':
        return item.currentStep || '审批中';
      default:
        return '';
    }
  };

  // 渲染审批列表项
  const renderApprovalItem = useCallback(({ item }: { item: ApprovalItem }) => {
    const statusInfo = getStatusInfo(item.status);
    
    return (
      <TouchableOpacity
        style={styles.approvalItem}
        onPress={() => handleApprovalItemPress(item)}
        activeOpacity={0.7}
      >
        <View style={styles.approvalItemHeader}>
          <View style={styles.approvalItemInfo}>
            <Text style={styles.approvalItemTitle}>{item.title}</Text>
            <Text style={styles.approvalItemTime}>{item.createTime}</Text>
          </View>
          <View style={[styles.statusBadge, statusInfo.style]}>
            <Text style={styles.statusText}>{statusInfo.text}</Text>
          </View>
        </View>
        
        <View style={styles.approvalItemFooter}>
          <View style={styles.approvalItemStatus}>
            {getStatusIcon(item)}
            <Text style={styles.approvalItemDescription}>
              {getStatusDescription(item)}
            </Text>
          </View>
          <FontAwesome6 name="chevron-right" size={14} color="#6B7280" />
        </View>
      </TouchableOpacity>
    );
  }, [handleApprovalItemPress]);

  // 渲染空状态
  const renderEmptyState = useCallback(() => (
    <View style={styles.emptyState}>
      <LinearGradient
        colors={['#969FFF', '#5147FF']}
        style={styles.emptyStateIcon}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
      >
        <FontAwesome5 name="file-alt" size={24} color="#FFFFFF" />
      </LinearGradient>
      <Text style={styles.emptyStateTitle}>暂无发起记录</Text>
      <Text style={styles.emptyStateDescription}>您还没有发起过任何审批</Text>
    </View>
  ), []);

  // 渲染列表头部
  const renderListHeader = useCallback(() => (
    <View style={styles.listHeader} />
  ), []);

  // 渲染列表尾部
  const renderListFooter = useCallback(() => (
    <View style={styles.loadMoreContainer}>
      <TouchableOpacity
        style={styles.loadMoreButton}
        onPress={handleLoadMore}
        disabled={isLoadingMore}
      >
        <Text style={styles.loadMoreText}>
          {isLoadingMore ? '加载中...' : '加载更多'}
        </Text>
      </TouchableOpacity>
    </View>
  ), [handleLoadMore, isLoadingMore]);

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <View style={styles.headerTop}>
          <Text style={styles.headerTitle}>我发起的</Text>
          <View style={styles.headerActions}>
            <TouchableOpacity
              style={styles.headerActionButton}
              onPress={handleSearchPress}
            >
              <FontAwesome5 name="search" size={18} color="#6B7280" />
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.headerActionButton}
              onPress={handleFilterPress}
            >
              <FontAwesome6 name="filter" size={18} color="#6B7280" />
            </TouchableOpacity>
          </View>
        </View>
        
        {/* 搜索框 */}
        {isSearchVisible && (
          <View style={styles.searchContainer}>
            <View style={styles.searchInputWrapper}>
              <FontAwesome5 
                name="search" 
                size={16} 
                color="#6B7280" 
                style={styles.searchIcon} 
              />
              <TextInput
                style={styles.searchInput}
                placeholder="搜索审批标题..."
                value={searchKeyword}
                onChangeText={handleSearchChange}
                autoFocus
              />
              <TouchableOpacity
                style={styles.searchCloseButton}
                onPress={handleSearchClose}
              >
                <FontAwesome5 name="times" size={16} color="#6B7280" />
              </TouchableOpacity>
            </View>
          </View>
        )}
      </View>

      {/* 审批列表 */}
      <FlatList
        data={approvalList}
        renderItem={renderApprovalItem}
        keyExtractor={(item) => item.id}
        ListHeaderComponent={renderListHeader}
        ListFooterComponent={renderListFooter}
        ListEmptyComponent={renderEmptyState}
        contentContainerStyle={styles.listContainer}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            colors={['#969FFF']}
            tintColor="#969FFF"
          />
        }
      />

      {/* 筛选模态框 */}
      <Modal
        visible={isFilterModalVisible}
        transparent
        animationType="slide"
        onRequestClose={handleFilterClose}
      >
        <View style={styles.filterModalOverlay}>
          <TouchableOpacity
            style={styles.filterModalBackdrop}
            onPress={handleFilterClose}
            activeOpacity={1}
          />
          <View style={styles.filterModalContent}>
            <View style={styles.filterModalHeader}>
              <Text style={styles.filterModalTitle}>筛选和排序</Text>
              <TouchableOpacity
                style={styles.filterModalCloseButton}
                onPress={handleFilterClose}
              >
                <FontAwesome5 name="times" size={20} color="#6B7280" />
              </TouchableOpacity>
            </View>
            
            {/* 状态筛选 */}
            <View style={styles.filterSection}>
              <Text style={styles.filterSectionTitle}>审批状态</Text>
              <View style={styles.filterStatusContainer}>
                {[
                  { key: 'all' as FilterStatus, label: '全部' },
                  { key: 'pending' as FilterStatus, label: '待审批' },
                  { key: 'processing' as FilterStatus, label: '审批中' },
                  { key: 'approved' as FilterStatus, label: '已通过' },
                  { key: 'rejected' as FilterStatus, label: '已驳回' },
                ].map((status) => (
                  <TouchableOpacity
                    key={status.key}
                    style={[
                      styles.filterStatusButton,
                      selectedFilterStatus === status.key && styles.filterStatusButtonActive
                    ]}
                    onPress={() => handleFilterStatusSelect(status.key)}
                  >
                    <Text
                      style={[
                        styles.filterStatusButtonText,
                        selectedFilterStatus === status.key && styles.filterStatusButtonTextActive
                      ]}
                    >
                      {status.label}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>
            </View>
            
            {/* 排序方式 */}
            <View style={styles.filterSection}>
              <Text style={styles.filterSectionTitle}>排序方式</Text>
              <View style={styles.filterSortContainer}>
                {[
                  { key: 'time-desc' as SortType, label: '按时间倒序' },
                  { key: 'time-asc' as SortType, label: '按时间正序' },
                  { key: 'status' as SortType, label: '按状态排序' },
                ].map((sort) => (
                  <TouchableOpacity
                    key={sort.key}
                    style={styles.filterSortItem}
                    onPress={() => handleSortTypeSelect(sort.key)}
                  >
                    <View style={styles.filterSortRadio}>
                      {selectedSortType === sort.key && (
                        <View style={styles.filterSortRadioInner} />
                      )}
                    </View>
                    <Text style={styles.filterSortLabel}>{sort.label}</Text>
                  </TouchableOpacity>
                ))}
              </View>
            </View>
            
            {/* 确定按钮 */}
            <TouchableOpacity
              style={styles.filterApplyButton}
              onPress={handleFilterApply}
            >
              <LinearGradient
                colors={['#969FFF', '#5147FF']}
                style={styles.filterApplyButtonGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <Text style={styles.filterApplyButtonText}>确定</Text>
              </LinearGradient>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
};

export default MyInitiatedScreen;

